package param

import (
	"bytes"
	"code.google.com/awwwe-browser/data"
	"fmt"
	"net/http/cookiejar"
	"net/url"
	"os"
	"path"
)

const (
	StartPath string = "/"
)

var (
	Scheme           string
	Host             string
	Port             int
	Package          string
	HomeURL          string
	BrowserCookieJar *cookiejar.Jar
)

func HostPort() string {
	return fmt.Sprintf("%s:%d", Host, Port)
}

func SetSchemeHostPortPackage(scheme, host string, port int, pack string) {
	var u url.URL
	Host = host
	Port = port
	Scheme = scheme
	Package = pack
	u.Scheme = scheme
	u.Host = HostPort()
	u.Path = fmt.Sprintf("/%s/", Package)
	HomeURL = u.String()
}

func init() {
	var cwd string
	var err error
	cwd, err = os.Getwd()
	if err == nil {
		LocalVOISFolderPath = path.Join(cwd, "vois")
		LocalBookmarkFilePath = path.Join(cwd, "bookmarks.json")
		LocalTabFilePath = path.Join(cwd, "tabs.xml")
		LocalSettingFilePath = path.Join(cwd, "settings.json")
		LocalFeedFilePath = path.Join(cwd, "feeds.json")
		LocalFeedItemFilePath = path.Join(cwd, "feeditems.json")
	} else {
		LocalVOISFolderPath = data.EmptyString
		LocalBookmarkFilePath = data.EmptyString
		LocalTabFilePath = data.EmptyString
		LocalSettingFilePath = data.EmptyString
		LocalFeedFilePath = data.EmptyString
		LocalFeedItemFilePath = data.EmptyString
	}
	BrowserCookieJar, _ = cookiejar.New(nil)
}

const (
	LocalVOISFileExt string = "_vois.xml"
)

var (
	LocalVOISFolderPath   string
	LocalBookmarkFilePath string
	LocalTabFilePath      string
	LocalSettingFilePath  string
	LocalFeedFilePath     string
	LocalFeedItemFilePath string
)

// EndSentence makes sure that there is punctuation ending the text.
func EndSentence(sentence string) string {
	var rr []rune
	var r rune
	var length int
	var bfr *bytes.Buffer
	rr = bytes.Runes([]byte(sentence))
	length = len(rr)
	if length > 1 {
		r = rr[length-1]
		if r != '.' && r != '!' && r != '?' {
			rr = append(rr, '.')
			// convert runes to bytes to a string
			bfr = bytes.NewBuffer(data.EmptyBytes)
			for _, r = range rr {
				bfr.WriteRune(r)
			}
			return bfr.String()
		}
	}
	return sentence
}
